<?php
/** ***********************
 * 作者：Zpy
 * 日期：2016/11/29
 * 作用：发票类
 ** ***********************/

class Ticket{
	public $appkey;
//	public $api_url = 'http://fapiao/ticket/'; 
	public $api_url = 'http://ticket.xiangfubao.com.cn/ticket/'; 
	function __construct($config){
		$this->appkey     =  $config['appkey'];
		$this->timestamp  =  time();
	}
	function test($str){
		return $str;
	}
	//查询发票信息
	function getTicketInfo($data){
		
		$post_data = array(
			'number'=>$data['number'],
			'appkey'=>$this->appkey,
		);
		$sign = $this->sign($post_data);
		$url = $this->api_url.'getTicketInfo.json?timestamp='.$this->timestamp.'&sign='.$sign;
		$return = $this->curlrequest($url,$post_data,'POST');
		return $return;
	}
	//开票
	function openTicket($data){
		
		$post_data = array(
			'orderNo'=>$data['orderNo'],
			'drawer'=>$data['drawer'],
			'collectorPhone'=>$data['collectorPhone'],
			'number'=>$data['orderNo'],
			'appkey'=>$this->appkey,
		);
		
		$sign = $this->sign($post_data);
		$url = $this->api_url.'openTicket.json?timestamp='.$this->timestamp.'&sign='.$sign;
		
		$return = $this->curlrequest($url,$post_data,'POST');
		return $return;
	}
	
	//查询
	function queryTicket($data){
		
		$post_data = array(
			'requestCode'=>$data['requestCode'],
			'number'=>$data['number'],
			'appkey'=>$this->appkey,
		);
		
		$sign = $this->sign($post_data);
		$url = $this->api_url.'queryTicket.json?timestamp='.$this->timestamp.'&sign='.$sign;
		
		$return = $this->curlrequest($url,$post_data,'POST');
		return $return;
	}
	
	//签名
	function sign($data){
		
		ksort($data);
		$str = '';
		unset($data['appkey']);
		foreach($data as $key=>$value)
		{
			if ($value){
				$str .= $key.'='.$value;
			}
			
		}
		
		$sign=MD5($str."timestamp=".$this->timestamp."appkey=".$this->appkey);
		return $sign;
	}
	//JSON转数组
	function jsontoarr($json){
		return json_decode($json,true);
	}
	//CURL请求
	function curlrequest($url,$data,$method='POST'){
		
		$ch = curl_init(); //初始化CURL句柄 
		curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出 
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
		curl_setopt($ch, CURLOPT_TIMEOUT,10);  
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
		
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
		
		
		/*curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		    'Content-Type: application/json; charset=utf-8',
		    'Content-Length: ' . strlen($data))
		);*/
		$document = curl_exec($ch);//执行预定义的CURL 
		if(!curl_errno($ch)){ 
		  $info = curl_getinfo($ch); 
			//echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']; 
		} else { 
		  echo 'Curl error: ' . curl_error($ch); 
		}
		
//		print_r('<pre>');
//		print_r($document);
//		print_r('</pre>');
//		
		
		curl_close($ch);
		return $this->jsontoarr($document);
	}
	
	
	
	
}